#include <mysql/mysql.h>
#include <string>
#include <iostream>
using namespace std;

class ConnectMysql
{
private:
    std::string userName = "zhiang";
    std::string host = "localhost";
    std::string password = "12345678.";
    std::string dbName = "conn";
    int port = 1314;
    MYSQL* my;
public:
    ConnectMysql()
    {
        my = mysql_init(nullptr);
        my = mysql_real_connect(my, host.c_str(), userName.c_str(), password.c_str(), dbName.c_str(), port, nullptr, 0);
        std::cout << "connect ok" << std::endl;
    }
    std::string Execute(const char * cmd)
    {
        std::string ret;
        std::cout << "cmd:" << cmd << std::endl;
        if(my == nullptr) std::cout << "my is nullptr" << std::endl;
        if(mysql_query(my, cmd))
        {
            cerr << "mysql_query failed: " << mysql_error(my) << endl;
            if(my == nullptr) std::cout << "my is nullptr" << std::endl;
            return "cmd error";
        }
        MYSQL_RES* res = mysql_store_result(my);
        if(nullptr == res) return "OK";

        int rows = mysql_num_rows(res);
        int fields = mysql_num_fields(res);
        MYSQL_FIELD* fields_array = mysql_fetch_fields(res);

        for(int i = 0; i < fields; i++)

        {
            ret += fields_array[i].name;
            ret += " ";
        }
        ret += '\n'; 
        
        for(int i = 0; i < rows; i++)
        {
            MYSQL_ROW row = mysql_fetch_row(res);
            for(int j = 0; j < fields; j++)
            {
                ret += row[j];
                ret += ' ';
            }
            ret += '\n';
        }

        mysql_free_result(res);
        return ret;
    }
    ~ConnectMysql()
    {
        mysql_close(my);
    }
};